<template>
    <div class="activity-manage">
        <div class="filter-container">
            <el-input v-model="listQuery.title" placeholder="搜索活动标题" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.activityType" placeholder="活动类型" clearable style="width: 120px"
                class="filter-item">
                <el-option label="讲座" :value="1" />
                <el-option label="赛事" :value="2" />
                <el-option label="培训" :value="3" />
            </el-select>
            <el-select v-model="listQuery.status" placeholder="活动状态" clearable style="width: 120px" class="filter-item">
                <el-option label="报名中" :value="0" />
                <el-option label="进行中" :value="1" />
                <el-option label="已结束" :value="2" />
            </el-select>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                发布活动
            </el-button>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column align="center" label="ID" width="80">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="活动标题" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <router-link :to="'/activity/detail/' + scope.row.id" class="link-type">
                        <el-tooltip :content="scope.row.title" placement="top" :disabled="scope.row.title.length <= 15">
                            <span class="title-text">{{ scope.row.title }}</span>
                        </el-tooltip>
                    </router-link>
                </template>
            </el-table-column>
            <el-table-column label="活动类型" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.activityType)">
                        {{ getTypeLabel(scope.row.activityType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="发布者" width="100" align="center">
                <template slot-scope="scope">
                    {{ scope.row.publishName }}
                </template>
            </el-table-column>
            <el-table-column label="开始时间" width="160" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span>{{ scope.row.startTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="报名截止" width="160" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span>{{ scope.row.registrationDeadline | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="报名状态" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getRegistrationStatusTagType(scope.row)">
                        {{ getRegistrationStatusLabel(scope.row) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="报名人数" width="100" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants || '∞' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="删除状态" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getDeleteStatusTagType(scope.row.deleted)" size="small">
                        {{ getDeleteStatusLabel(scope.row.deleted) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="附件" width="120" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-dropdown v-if="scope.row.attachments && scope.row.attachments.length > 0"
                        @command="handleDownloadAttachment">
                        <el-button type="text" size="mini">
                            <i class="el-icon-paperclip"></i>
                            附件 ({{ scope.row.attachments.length }})
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                :command="{ file, activity: scope.row }">
                                <i :class="getFileIcon(file.name)"></i>
                                {{ file.name }}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span v-else class="no-attachment">无附件</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="300" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleView(scope.row)">
                        查看
                    </el-button>
                    <el-button v-if="scope.row.status === 1" type="warning" size="mini" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button v-if="scope.row.currentParticipants > 0" type="success" size="mini"
                        @click="handleExport(scope.row)">
                        导出名单
                    </el-button>
                    <el-button
                        v-if="scope.row.status === 1 && scope.row.currentParticipants === 0 && scope.row.deleted === 0"
                        type="danger" size="mini" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
            @pagination="getList" />
    </div>
</template>

<script>
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { getCurrnetUserActivityList, deleteActivity, exportParticipantsList } from '@/api/activity'
export default {
    name: 'ActivityManage',
    components: { Pagination },
    filters: {
        parseTime
    },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                pageNo: 1,
                pageSize: 20,
                title: undefined,
                activityType: undefined,
                status: undefined
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        // 获取当前教师活动列表
        async getList() {
            try {
                this.listLoading = true
                const res = await getCurrnetUserActivityList(this.listQuery)
                this.total = res.data.total || 0;
                res.data.records.forEach(item => {
                    item.attachments = JSON.parse(item.attachmentUrl || '[]')
                });
                this.list = res.data.records || []
            } catch (error) {
                console.error(error)
            } finally {
                this.listLoading = false
            }
        },
        handleFilter() {
            this.listQuery.pageNo = 1
            this.getList()
        },
        handleCreate() {
            this.$router.push('/activity/publish')
        },
        handleView(row) {
            this.$router.push(`/activity/detail/${row.id}`)
        },
        handleEdit(row) {
            this.$router.push(`/activity/publish?id=${row.id}`)
        },
        async handleDelete(row) {
            try {
                await this.$confirm(`确认删除活动"${row.title}"？删除后将无法恢复！`, '删除确认', {
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                this.listLoading = true
                const res = await deleteActivity(row.id)
                this.$message.success('活动删除成功！')
                // 刷新列表
                this.getList()
            } catch (error) {
                if (error === 'cancel') {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                } else {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败，请重试')
                }
            } finally {
                this.listLoading = false
            }

        },
        handleExport(row) {
            this.$confirm(`确认导出"${row.title}"的报名学生名单？`, '导出确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }).then(() => {
                this.exportParticipantsList(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消导出'
                })
            })
        },
        // 导出参与者名单
        async exportParticipantsList(activity) {
            try {
                // 检查活动是否有参与者
                if (activity.currentParticipants === 0) {
                    this.$message({
                        type: 'warning',
                        message: '该活动暂无参与者，无法导出'
                    })
                    return
                }

                this.$message({
                    type: 'info',
                    message: '正在导出，请稍候...'
                })

                console.log('开始导出活动:', activity.id, activity.title)

                // 调用API获取文件
                const response = await exportParticipantsList(activity.id)

                console.log('导出响应:', response)

                // 检查响应数据
                if (!response || !response.data) {
                    throw new Error('服务器返回数据为空')
                }

                // 检查是否是有效的文件数据
                if (response.data.size === 0) {
                    throw new Error('导出的文件为空')
                }

                // 从响应头获取文件名
                let fileName = `${activity.title}_参与者名单.xlsx`
                const contentDisposition = response.headers['content-disposition']
                if (contentDisposition) {
                    console.log('Content-Disposition:', contentDisposition)

                    // 处理 filename*=utf-8''encoded_filename 格式
                    const utf8Match = contentDisposition.match(/filename\*=utf-8''([^;]+)/)
                    if (utf8Match && utf8Match[1]) {
                        fileName = decodeURIComponent(utf8Match[1])
                        console.log('解析的UTF-8文件名:', fileName)
                    } else {
                        // 处理普通的 filename="filename" 格式
                        const normalMatch = contentDisposition.match(/filename=['"]?([^'";]+)['"]?/)
                        if (normalMatch && normalMatch[1]) {
                            fileName = normalMatch[1]
                            console.log('解析的普通文件名:', fileName)
                        }
                    }
                }

                console.log('文件名:', fileName)

                // 创建Blob并下载
                const blob = new Blob([response.data], {
                    type: 'application/vnd.ms-excel'
                })

                // 创建下载链接
                const downloadUrl = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.href = downloadUrl
                link.download = fileName
                link.style.display = 'none'

                // 触发下载
                document.body.appendChild(link)
                link.click()

                // 清理
                setTimeout(() => {
                    document.body.removeChild(link)
                    window.URL.revokeObjectURL(downloadUrl)
                }, 100)

                this.$message({
                    type: 'success',
                    message: '导出成功！'
                })
            } catch (error) {
                console.error('导出失败详情:', error)

                let errorMessage = '导出失败，请重试'
                if (error.response) {
                    console.error('错误响应:', error.response)
                    if (error.response.status === 404) {
                        errorMessage = '导出接口不存在'
                    } else if (error.response.status === 401) {
                        errorMessage = '认证失败，请重新登录'
                    } else if (error.response.status === 500) {
                        errorMessage = '服务器内部错误'
                    }
                } else if (error.message) {
                    errorMessage = error.message
                }

                this.$message({
                    type: 'error',
                    message: errorMessage
                })
            }
        },
        handleDownloadAttachment(command) {
            const { file, activity } = command
            // 创建下载链接
            const link = document.createElement('a')
            link.href = file.url
            link.download = file.name
            link.target = '_blank'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.$message.success(`开始下载：${file.name}`)
        },
        getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase()
            const iconMap = {
                pdf: 'el-icon-document',
                doc: 'el-icon-document',
                docx: 'el-icon-document',
                xls: 'el-icon-s-grid',
                xlsx: 'el-icon-s-grid',
                ppt: 'el-icon-picture-outline',
                pptx: 'el-icon-picture-outline',
                txt: 'el-icon-document-copy',
                zip: 'el-icon-folder-opened',
                rar: 'el-icon-folder-opened'
            }
            return iconMap[ext] || 'el-icon-document'
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '讲座',
                2: '赛事',
                3: '培训',
                // 兼容字符串格式
                lecture: '讲座',
                competition: '赛事',
                training: '培训'
            }
            return typeMap[type] || type
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                // 兼容字符串格式
                lecture: 'primary',
                competition: 'success',
                training: 'warning'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                1: '发布',
                2: '结束',
                3: '取消',
                // 兼容字符串格式
                draft: '草稿',
                registering: '报名中',
                ongoing: '进行中',
                finished: '已结束'
            }
            return statusMap[status] || status
        },
        getStatusTagType(status) {
            const statusMap = {
                1: 'success',    // 发布 - 绿色
                2: 'warning',    // 结束 - 橙色
                3: 'danger',     // 取消 - 红色
                // 兼容字符串格式
                draft: 'info',
                registering: 'success',
                ongoing: 'warning',
                finished: 'info'
            }
            return statusMap[status] || ''
        },
        // 获取报名状态标签文本
        getRegistrationStatusLabel(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态，直接返回对应状态
            if (row.status !== 1) {
                return this.getStatusLabel(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return '已结束'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return '进行中'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return '报名截止'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return '已满员'
                }
                return '报名中'
            }

            return '未知'
        },
        // 获取报名状态标签类型
        getRegistrationStatusTagType(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态
            if (row.status !== 1) {
                return this.getStatusTagType(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return 'info'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return 'success'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return 'warning'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return 'danger'
                }
                return 'primary'
            }

            return ''
        },
        // 获取删除状态标签文本
        getDeleteStatusLabel(deleted) {
            const statusMap = {
                0: '未删除',
                1: '已删除'
            }
            return statusMap[deleted] || '未知'
        },
        // 获取删除状态标签类型
        getDeleteStatusTagType(deleted) {
            const statusMap = {
                0: 'success',    // 未删除 - 绿色
                1: 'danger'      // 已删除 - 红色
            }
            return statusMap[deleted] || ''
        }
    }
}
</script>

<style lang="scss" scoped>
.activity-manage {
    padding: 20px;
}

.filter-container {
    padding-bottom: 10px;

    .filter-item {
        display: inline-block;
        vertical-align: middle;
        margin-bottom: 10px;
        margin-right: 10px;
    }
}

.link-type {
    color: #409EFF;
    text-decoration: none;
    display: block;

    &:hover {
        color: #66b1ff;
    }

    .title-text {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: top;
    }
}

.dialog-footer {
    text-align: right;
}

.no-attachment {
    color: #c0c4cc;
    font-size: 12px;
}

::v-deep .el-dropdown {
    .el-button--text {
        color: #409EFF;

        &:hover {
            color: #66b1ff;
        }
    }
}

::v-deep .el-dropdown-menu__item {
    padding: 8px 16px;

    i {
        margin-right: 8px;
        color: #409EFF;
    }

    &:hover {
        background-color: #ecf5ff;
        color: #409EFF;
    }
}
</style>
